// dart_type_system_examples_refactored.dart

import 'dart:async'; // For Stream (async* generator)

// --- 1. 基础类型安全与静态分析 Helpers ---

// 用于 isNoble 函数示例
const _nobleGases = {
  2: 'Helium',
  10: 'Neon',
  18: 'Argon',
  36: 'Krypton',
  54: 'Xenon',
  86: 'Radon',
};

// 基础函数示例
bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

// 箭头函数示例
bool isNobleShort(int atomicNumber) => _nobleGases[atomicNumber] != null;

// 一个接受整数列表的函数
void printInts(List<int> a) => print('printInts: $a');

// --- 2. 类与继承 Helpers ---

// 动物基类
class Animal {
  void chase(Animal a) {
    print('Animal chasing another Animal');
  }

  // 使用可空类型更实际
  Animal? get parent => null;

  @override
  String toString() => runtimeType.toString(); // 方便打印类型
}

// 蜜獾类，继承自动物 (正确的顶级定义)
class HoneyBadger extends Animal {
  @override
  void chase(Object a) {
    // 参数类型放宽 (Object 是 Animal 的父类型) - OK
    print('HoneyBadger chasing an Object: $a');
  }

  @override
  HoneyBadger? get parent => null; // 返回值类型收窄 (HoneyBadger 是 Animal 的子类型) - OK
}

// 鼠标类
class Mouse extends Animal {}

// 猫类
class Cat extends Animal {
  // @override
  // void chase(Mouse a) { // 错误: 参数类型不能收窄 (Mouse 是 Animal 的子类型)
  //   print('Cat chasing a Mouse');
  // }
  // 上面的代码会产生静态分析错误，除非使用 covariant (见下文 Covariant 示例)

  @override
  void chase(Animal a) {
    // 保持父类参数类型
    if (a is Mouse) {
      print('Cat chasing a specific Mouse!');
    } else {
      print('Cat chasing an Animal');
    }
  }
}

// 缅因猫类
class MaineCoon extends Cat {}

// 狗类
class Dog extends Animal {}

// --- 3. F-Bounded 类型 Helpers ---
class A_FBounded<
  X extends A_FBounded<X>
> {} // Renamed to avoid conflict with class A

class B_FBounded extends A_FBounded<B_FBounded> {}

class C_FBounded extends B_FBounded {}

// 接受 F-Bounded 类型参数的函数
void f_fbounded<X extends A_FBounded<X>>(X x) {
  // Renamed to avoid conflict
  print('f_fbounded<$X> called with instance of type ${x.runtimeType}');
}

// --- 4. Comparable 示例 Helper ---
// 查找两个可比较对象中较大的一个
// X 必须是 Comparable<X> 的子类型
X max<X extends Comparable<X>>(X x1, X x2) {
  print('Comparing $x1 and $x2');
  return x1.compareTo(x2) > 0 ? x1 : x2;
}

// --- 5. 类型解构模拟 Helpers ---
// 辅助类 (替代 Record)
class Pair<T1, T2> {
  final T1 first;
  final T2 second;
  Pair(this.first, this.second);

  @override
  String toString() =>
      'Pair(first: $first [${first.runtimeType}], second: $second [${second.runtimeType}])';
}

// 模拟类型解构的函数
// X 是 Iterable<Y> 的子类型
Pair<X, Y> f1<X extends Iterable<Y>, Y>(X x) {
  print('f1 called with Iterable of type $X containing elements of type $Y');
  return Pair(x, x.first);
}

// --- 6. 静态字段推断 Helper ---
class Counter {
  // count 会被推断为 int 类型
  static var count = 0;
}

// --- 7. Covariant 示例 Helpers ---
class AnimalCovariant {
  void chase(AnimalCovariant x) {
    print('AnimalCovariant chasing AnimalCovariant');
  }
}

class MouseCovariant extends AnimalCovariant {}

class CatCovariant extends AnimalCovariant {
  // 使用 covariant 关键字允许参数类型收窄
  // 这会移除静态错误，但在运行时会进行检查
  @override
  void chase(covariant MouseCovariant x) {
    print('CatCovariant chasing a specific MouseCovariant');
  }
}

// --- 8. 类型别名 (Typedefs) ---
typedef IntList = List<int>;
typedef ListMapper<X> = Map<X, List<X>>;
typedef Compare<T> = int Function(T a, T b);

// 一个符合 Compare<int> 签名的函数
int sort(int a, int b) => a - b;

// --- 9. 函数定义与参数 Helpers ---

// 命名参数 - 可空
void enableFlagsNullable({bool? bold, bool? hidden}) {
  print('Flags Nullable: bold=${bold ?? 'null'}, hidden=${hidden ?? 'null'}');
}

// 命名参数 - 带默认值
void enableFlagsDefault({bool bold = false, bool hidden = false}) {
  print('Flags Default: bold=$bold, hidden=$hidden');
}

// 命名参数 - 必需 (模拟 Scrollbar)
// 简化版 Widget 类
class Widget {
  const Widget();
}

class Scrollbar extends Widget {
  final Widget child;
  // 使用 required 标记必需的命名参数
  const Scrollbar({required this.child});

  void display() {
    print('Displaying Scrollbar with child: ${child.runtimeType}');
  }
}

// 命名参数 - 位置随意 (模拟 repeat)
void repeat(Function action, {required int times}) {
  for (int i = 0; i < times; i++) {
    action();
  }
}

// 可选位置参数 - 可空
String sayNullable(String from, String msg, [String? device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

// 可选位置参数 - 带默认值
String sayDefault(String from, String msg, [String device = 'carrier pigeon']) {
  var result = '$from says $msg with a $device';
  return result;
}

// --- 10. 函数作为对象 Helpers ---

// 用于 forEach 示例
void printElement(int element) {
  print('Element: $element');
}

// 用于函数类型示例
void greet(String name, {String greeting = 'Hello'}) =>
    print('$greeting $name!');

// --- 11. 闭包 Helper ---
Function makeAdder(int addBy) {
  return (int i) => addBy + i;
}

// --- 12. 函数相等性测试 Helpers ---
void fooTopLevel() {} // 顶级函数

class A {
  // Class for equality test
  static void barStatic() {} // 静态方法
  void bazInstance() {} // 实例方法
}

// --- 13. 返回值 Helpers ---
// 用于隐式返回 null 示例
fooNullReturn() {}

// 用于返回 Record 示例
(String, int) fooRecordReturn() {
  return ('something', 42);
}

// --- 14. 生成器 Helpers ---
// 同步生成器
Iterable<int> naturalsTo(int n) sync* {
  print('Sync Generator naturalsTo started');
  int k = 0;
  while (k < n) {
    print('Yielding $k');
    yield k++;
  }
  print('Sync Generator naturalsTo finished');
}

// 异步生成器
Stream<int> asynchronousNaturalsTo(int n) async* {
  print('Async Generator asynchronousNaturalsTo started');
  int k = 0;
  while (k < n) {
    print('Yielding async $k');
    yield k++;
    // 模拟一些异步工作
    await Future.delayed(Duration(milliseconds: 100));
  }
  print('Async Generator asynchronousNaturalsTo finished');
}

// 递归生成器 (yield*)
Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    yield n;
    yield* naturalsDownFrom(n - 1); // 委托给另一个生成器
  }
}

// --- 15. 外部函数声明 ---
// external void someFunc(int i); // 需要平台特定的实现, 保持注释

// --- 16. 循环 Helpers ---

// 用于 for-in 和 continue 示例
class Candidate {
  final String name;
  final int yearsExperience;

  Candidate(this.name, this.yearsExperience);

  void interview() {
    print('Interviewing $name ($yearsExperience years)');
  }
}

// 模拟 while 循环条件
int _doneCounter = 0;
bool isDone() {
  _doneCounter++;
  print('Checking isDone() - call #$_doneCounter');
  return _doneCounter > 3; // Loop 3 times
}

void doSomething() {
  print('Doing something...');
}

// 模拟 do-while 循环条件
int _pageCounter = 0;
bool atEndOfPage() {
  _pageCounter++;
  print('Checking atEndOfPage() - call #$_pageCounter');
  return _pageCounter > 2; // Loop 2 times
}

void printLine() {
  print('Printing a line...');
}

// 模拟 break 循环条件
int _requestCounter = 0;
bool shutDownRequested() {
  _requestCounter++;
  print('Checking shutDownRequested() - call #$_requestCounter');
  return _requestCounter > 2; // Break after 2 iterations
}

void processIncomingRequests() {
  print('Processing requests...');
}

// --- 主函数入口 ---
void main() async {
  // 改为 async 以便 await 异步生成器

  print('--- 1. 基础类型安全与静态分析 ---');
  final listInt = <int>[];
  listInt.add(1);
  listInt.add(2);
  printInts(listInt);
  print('isNoble(10): ${isNoble(10)}');
  print('isNobleShort(18): ${isNobleShort(18)}');

  print('\n--- 2. 类、继承与方法重写 ---');
  final honeyBadger = HoneyBadger();
  honeyBadger.chase(Animal());
  HoneyBadger? parentBadger = honeyBadger.parent;
  print('HoneyBadger parent type: ${parentBadger?.runtimeType}');
  Cat().chase(Animal());

  print('\n--- 3. 动态列表与类型转换 ---');
  List<dynamic> bar = <dynamic>[Dog(), Cat()];
  print('Dynamic list bar: $bar');
  try {
    List<Animal> animals = <Dog>[Dog()];
    List<Cat> cats = animals as List<Cat>;
    print('Cats after cast (will not reach here): $cats');
  } catch (e) {
    print('Runtime cast error caught: $e');
  }

  print('\n--- 4. 类型推断 ---');
  Map<String, dynamic> argumentsExplicit = {'argA': 'hello', 'argB': 42};
  var argumentsInferred = {'argA': 'hello', 'argB': 42};
  print(
    'Explicit Map: $argumentsExplicit, Type: ${argumentsExplicit.runtimeType}',
  );
  print(
    'Inferred Map: $argumentsInferred, Type: ${argumentsInferred.runtimeType}',
  );
  print('Static Counter.count type: ${Counter.count.runtimeType}');
  num yNum = 3;
  yNum = 4.0;
  print('Variable y_num: $yNum, Type: ${yNum.runtimeType}');
  // 移除未使用的变量 listOfInt
  var listOfDouble = [3.0];
  var ints = listOfDouble.map((x) => x.toInt());
  print('Inferred Iterable<int>: ${ints.toList()}, Type: ${ints.runtimeType}');

  print('\n--- 5. 类型推断 (Bounds) ---');
  f_fbounded(B_FBounded());
  f_fbounded(C_FBounded());
  f_fbounded<B_FBounded>(C_FBounded());
  var maxNum = max(3, 7);
  print('Max of 3 and 7 is $maxNum, Type: ${maxNum.runtimeType}');
  var maxInt = max(5, 2);
  print('Max of 5 and 2 is $maxInt, Type: ${maxInt.runtimeType}');
  var result1 = f1([1, 2, 3]);
  print('f1 result for List: $result1');
  var myInt = result1.second;
  print('Extracted int: $myInt, Type: ${myInt.runtimeType}');
  var result2 = f1({'Hello!'});
  print('f1 result for Set: $result2');
  var mySet = result2.first;
  print('Extracted Set: $mySet, Type: ${mySet.runtimeType}');
  var unionSet = mySet.union({'World!'});
  print('Union Set: $unionSet');

  print('\n--- 6. 类型替换 (协变与逆变) ---');
  Animal c1 = Cat();
  print('Consumer widening: c1 is ${c1.runtimeType}');
  Cat c3 = MaineCoon();
  print('Producer narrowing: c3 is ${c3.runtimeType}');
  List<MaineCoon> myMaineCoons = [MaineCoon()];
  List<Cat> myCatsFromMC = myMaineCoons;
  print(
    'Generic covariant assignment: myCatsFromMC holds ${myCatsFromMC.runtimeType}',
  );
  List<Animal> myAnimals = [Dog(), Cat()];
  try {
    List<Cat> myCatsFromAnimalExplicit = myAnimals as List<Cat>;
    print(
      'Explicit cast result (potential runtime error): $myCatsFromAnimalExplicit',
    );
  } catch (e) {
    print('Runtime cast error for List caught: $e');
  }

  print('\n--- 7. Covariant 关键字 ---');
  var catCov = CatCovariant();
  var mouseCov = MouseCovariant();
  catCov.chase(mouseCov);

  print('\n--- 8. 类型别名 (Typedef) ---');
  IntList il = [1, 2, 3];
  print('Using IntList typedef: $il, Type: ${il.runtimeType}');
  printInts(il);
  Map<String, List<String>> m1 = {
    'a': ['A'],
    'b': ['B'],
  };
  ListMapper<String> m2 = {
    'c': ['C'],
    'd': ['D'],
  };
  print('Verbose Map: $m1, Type: ${m1.runtimeType}');
  print('Typedef Map: $m2, Type: ${m2.runtimeType}');
  // 由于 sort 函数的签名已经完全匹配 Compare<int>，这个断言是多余的
  print('sort function is of type Compare<int>');
  print('Assertion passed: sort function is indeed a Compare<int>!');

  print('\n--- 9. 函数参数 ---');
  print('Named Parameters (Nullable):');
  enableFlagsNullable(bold: true);
  enableFlagsNullable(hidden: false);
  enableFlagsNullable();
  print('Named Parameters (Default Value):');
  enableFlagsDefault(bold: true);
  enableFlagsDefault();
  print('Named Parameters (Required):');
  var myScrollbar = Scrollbar(child: Widget());
  myScrollbar.display();
  print('Named Parameters (Anywhere):');
  repeat(() {
    print('Repeating action!');
  }, times: 2);
  print('Optional Positional Parameters (Nullable):');
  print(sayNullable('Bob', 'Howdy'));
  print(sayNullable('Bob', 'Howdy', 'smoke signal'));
  print('Optional Positional Parameters (Default Value):');
  print(sayDefault('Alice', 'Hi'));
  print(sayDefault('Alice', 'Hi', 'telegram'));

  print('\n--- 10. 函数作为一等公民 ---');
  var listForFunc = [10, 20, 30];
  print('Passing function tear-off to forEach:');
  listForFunc.forEach(printElement);
  loudify(msg) => '!!! ${msg.toUpperCase()} !!!';
  print('Assigning function to variable: ${loudify('hello')}');
  void Function(String, {String greeting}) g = greet;
  print('Calling function via typed variable:');
  g('Dash', greeting: 'Howdy');
  g('World');

  print('\n--- 11. 匿名函数与闭包 ---');
  const listAnon = ['apples', 'bananas', 'oranges'];
  var uppercaseList = listAnon.map((item) => item.toUpperCase()).toList();
  print('Uppercase list: $uppercaseList');
  print('Printing uppercase items and lengths:');
  for (var item in uppercaseList) {
    print('$item: ${item.length}');
  }
  var add2 = makeAdder(2);
  var add4 = makeAdder(4);
  print('Closure add2(3) = ${add2(3)}');
  print('Closure add4(3) = ${add4(3)}');

  print('\n--- 12. Tear-offs ---');
  var charCodes = [68, 97, 114, 116];
  var buffer = StringBuffer();
  print('Using print tear-off:');
  charCodes.forEach(print);
  print('Using buffer.write tear-off:');
  charCodes.forEach(buffer.write);
  print('Buffer content after tear-off writes: "${buffer.toString()}"');

  print('\n--- 13. 函数相等性测试 ---');
  Function x;
  x = fooTopLevel;
  assert(fooTopLevel == x);
  print('Top-level function equality test passed.');
  x = A.barStatic;
  assert(A.barStatic == x);
  print('Static method equality test passed.');
  var v = A();
  var w = A();
  var instanceY = w;
  x = w.bazInstance;
  assert(
    instanceY.bazInstance == x,
    'Tear-offs from same instance should be equal',
  );
  print('Instance method tear-off equality (same instance) test passed.');
  assert(
    v.bazInstance != w.bazInstance,
    'Tear-offs from different instances should be unequal',
  );
  print(
    'Instance method tear-off inequality (different instances) test passed.',
  );

  print('\n--- 14. 返回值 ---');
  print('Calling fooNullReturn(): ${fooNullReturn()}');
  var recordResult = fooRecordReturn();
  print(
    'Calling fooRecordReturn(): $recordResult, Type: ${recordResult.runtimeType}',
  );
  print('Accessing record elements: ${recordResult.$1}, ${recordResult.$2}');

  print('\n--- 15. 生成器 (Generators) ---');
  print('Iterating over sync* sequence:');
  var sequence = naturalsTo(3);
  for (var value in sequence) {
    print('Received sync value: $value');
  }
  print('Listening to async* stream:');
  var stream = asynchronousNaturalsTo(3);
  await for (var value in stream) {
    print('Received async value: $value');
  }
  print('Iterating over yield* sequence:');
  var recursiveSequence = naturalsDownFrom(4);
  print('Recursive sequence result: ${recursiveSequence.toList()}');

  print('\n--- 16. 外部函数 ---');
  print(
    '(External function declarations exist but cannot be called without implementation)',
  );

  print('\n--- 17. 循环 (Loops) ---');

  print('\nStandard for loop:');
  var message = StringBuffer('Dart is fun');
  for (var i = 0; i < 5; i++) {
    message.write('!');
  }
  print(message); // Dart is fun!!!!!

  print('\nFor loop closure behavior:');
  var callbacks = [];
  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print('Callback prints: $i')); // 闭包捕获索引值
  }
  for (final c in callbacks) {
    c(); // 输出 0 和 1
  }

  // 准备 Candidate 数据
  final candidates = [
    Candidate('Alice', 8),
    Candidate('Bob', 3),
    Candidate('Charlie', 10),
    Candidate('David', 4),
  ];

  print('\nFor-in loop:');
  for (final candidate in candidates) {
    candidate.interview(); // 调用每个 candidate 的 interview 方法
  }

  print('\nFor-in loop with pattern matching:');
  for (final Candidate(:name, :yearsExperience) in candidates) {
    print('$name has $yearsExperience of experience.'); // 使用模式匹配提取属性
  }

  print('\nforEach method:');
  var collection = [101, 102, 103];
  collection.forEach(print); // 使用 forEach 打印每个元素

  print('\nWhile loop:');
  _doneCounter = 0; // Reset counter for demo
  while (!isDone()) {
    // 条件在循环前检查
    doSomething();
  }

  print('\nDo-while loop:');
  _pageCounter = 0; // Reset counter for demo
  do {
    printLine();
  } while (!atEndOfPage()); // 条件在循环后检查

  print('\nBreak statement:');
  _requestCounter = 0; // Reset counter for demo
  while (true) {
    // 无限循环
    if (shutDownRequested()) {
      print('Shutdown requested, breaking loop.');
      break; // 跳出循环
    }
    processIncomingRequests();
  }

  print('\nContinue statement:');
  for (int i = 0; i < candidates.length; i++) {
    var candidate = candidates[i];
    if (candidate.yearsExperience < 5) {
      print('Skipping ${candidate.name} (experience < 5 years).');
      continue; // 跳过当前迭代的剩余部分，进入下一次迭代
    }
    candidate.interview(); // 只面试经验 >= 5 年的
  }

  print('\nIterable where/forEach alternative for continue:');
  candidates
      .where((c) => c.yearsExperience >= 5) // 先过滤
      .forEach((c) => c.interview()); // 再对过滤后的结果执行操作

  print('\n--- 示例代码执行完毕 ---');
}
